
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Award2 extends CI_Controller {

 	public function __construct()
	{
        parent::__construct();
        $this->load->database();
        $this->load->helper('cookie');
    }

	public function index()
	{
		$query = $this->db->select('openid,username,headimgurl')->get_where('quiz',array('is_award'=>0))->result_array();
		echo json_encode($query);
	}

	public function get_count()
	{
		echo $this->db->count_all('quiz');
	}

	public function get_award_list(){
		$list = $this->db->select('id,openid,username,headimgurl')->get_where('quiz',array('is_award'=>1))->result_array();
		echo json_encode($list);
	} 


	public function get_award_user()
	{
		
		$award = $this->db->select('id,openid,username,headimgurl')->get_where('quiz',array('is_award'=>1))->result_array();
		if(count($award)>=20){
			exit(json_encode(array('code'=>-1)));
		}

		$query = $this->db->select('id,openid,username,headimgurl')->get_where('quiz',array('is_award'=>0))->result_array();

		//要跟新的id集合
		$strID = '';
		//返回到前端的中奖集合
		$list = array();

		$queryCount = count($query);
		if ($queryCount<=5) 
		{
			foreach ($query as $key => $value) 
			{
				if ($queryCount==$key+1) 
				{
					$strID .= $value['id'];
				}
				else
				{
					$strID .= $value['id'].',';
				}
			}

			$list = $query;
		}
		else
		{
			//取出要使用抽奖人的五个下标
			$arr = array_rand($query,5);
			$allID[] = $query[$arr[0]]['id'];
			$allID[] = $query[$arr[1]]['id'];
			$allID[] = $query[$arr[2]]['id'];
			$allID[] = $query[$arr[3]]['id'];
			$allID[] = $query[$arr[4]]['id'];
			$strID = implode(',', $allID);

			$list[] = $query[$arr[0]];
			$list[] = $query[$arr[1]];
			$list[] = $query[$arr[2]];
			$list[] = $query[$arr[3]];
			$list[] = $query[$arr[4]];
		}
		
		$count = 0;
		if ($strID) 
		{
			$sql = "UPDATE quiz SET is_award=1 WHERE id IN ({$strID})";
			$this->db->query($sql);
			$count = $this->db->affected_rows();
		}
		
		echo json_encode($list);
	}

}

/* End of file Award.php */
/* Location: ./application/controllers/Award.php */
?>